var express = require('express');
var router = express.Router();
// 数据库
var userDAO = require("../bin/cn/userDAO.js");
var diaryDAO = require("../bin/cn/diaryDAO.js");
var logDAO = require("../bin/cn/logDAO.js");
var replyDAO = require("../bin/cn/replyDAO.js");
// 导入时间函数
var newtime = require("../bin/libs/time.js");
var isLogin = require("../bin/libs/isLogin.js");


// 导入文件上传模块
var multer = require("multer");
var storage = multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'./public/img/day');
    },
    filename:function(req,file,cb){
        var suffix = file.mimetype.split("/")[1];
        var namr = file.fieldname + '-'+Date.now()+'.'+suffix;
        cb(null,namr);
        req.arr="/img/day/"+namr;
    }
});
var upload = multer({storage:storage});

// 添加日记本
router.post("/add",(req,res)=>{
    var date = req.body.expire;
    date = new Date(Date.parse(date.replace(/-/g, "/")));
    date = date.getTime();
    var timestamp = Date.parse(new Date())+ 7*24*60*60*1000;
    if(date<timestamp){
        res.json({err:1,msg:"日期最低8天时间"});
        return;
    }
    req.body.userID = req.session.user._id;
    req.body.time = newtime();
    diaryDAO.find({userID:req.body.userID,name:req.body.name})
    .then(datas=>{  
        if(datas.length>0){
            res.json({err:2,msg:"您已经有这个日记标题"});
        }else{
            var d = new diaryDAO(req.body);
            d.save()
            res.json({err:0,msg:"创建成功"});
        }
    })
});

// 查询我的日记本
router.get("/view",isLogin)
router.get("/view",(req,res)=>{
    diaryDAO.find({userID:req.session.user._id})
    .then(data=>{
        res.json({err:0,data:data});
    })
});

// 添加日记(不带照片)
router.get("/addlog",isLogin)
router.get("/addlog",(req,res)=>{
    var sj = newtime();
    req.query.day = sj.split(' ')[0];
    req.query.sj = sj.split(' ')[1];
    req.query.userID = req.session.user._id;
    req.query.reply = [];
    var l = new logDAO(req.query);
    l.save()
    .then(()=>{
        res.json({err:0,msg:"添加成功"});
    })
});

// 添加日记(带照片)
router.post("/addlog",isLogin)
router.post("/addlog",upload.single("day"),(req,res)=>{
    var sj = newtime();
    req.body.day = sj.split(' ')[0];
    req.body.sj = sj.split(' ')[1];
    req.body.userID = req.session.user._id;
    req.body.img = req.arr;
    req.query.reply = [];
    var l = new logDAO(req.body);
    l.save()
    .then(()=>{
        res.json({err:0,msg:"添加成功"});
    })
});

// 查看自己的日记--或点击别人的id
// router.get("/look",isLogin);
router.get("/look",(req,res)=>{
    if(req.query.id=="me"){
        if(!req.session.user){
            res.json({err:8});
            return;
        }
        req.query.id= req.session.user._id;
        var ss = {
            userID:req.session.user._id
        }
    }else{
        var ss = {
            userID:req.query.id,
            day:newtime().split(' ')[0],
        }
        if(req.session.user){
            if(req.query.id==req.session.user._id){
                delete ss.day;
            }
        }
    }
    logDAO.find(ss)
    .populate("diaryID")
    .then(data1=>{
        diaryDAO.find({userID:req.query.id})
        .then(data2=>{
            userDAO.findOne({_id:req.query.id})
            .then(data3=>{
                data1=data1.reverse();
                data2=data2.reverse();
                var data4 = {};
                if(req.session.user){
                    data4.isLogin = true;
                    data4.isMe =req.session.user._id==req.query.id;
                    if(!data4.isMe){
                        if(req.session.user.info.indexOf(data3._id.toString())==-1){
                            data4.info = false;
                        }else{
                            data4.info = true;
                        }
                    }
                }else{
                    data4.isLogin = false;
                    data4.isMe = false;
                }
                res.json({err:0,data:{data1:data1,data2:data2,data3:data3,data4}});
            })
        })
    })
});

// 查看所有日志
router.get("/home",(req,res)=>{
    logDAO.find()
    .sort({_id:-1})
    .skip((req.query.page)*(req.query.num))
    .limit(req.query.num*1)
    .populate("diaryID")
    .populate("userID",{psw:0})
    .then(data=>{
        
        res.json({err:0,data:data});
    })
})

// 日记详情页面
router.get("/reply",(req,res)=>{
    logDAO.findOne({_id:req.query.id})
    .populate("diaryID")
    // .populate("reply")
    .populate({
        path: 'reply',
        // model: 'sales',
        populate: {
            path: 'userID',
            // model: 'merchant'
        },
    })
    .populate("userID",{psw:0})
    .then(data=>{
        var data1 = {};
        if(req.session.user){          
            data1.isLogin = true;
            data1.isMe =req.session.user._id==data.userID._id;
            if(!data1.isMe){
                if(req.session.user.info.indexOf(data.userID._id.toString())==-1){
                    data1.info = false;
                }else{
                    data1.info = true;
                }
            }
        }else{
            data1.isLogin = false;
            data1.isMe = false;
        }
        res.json({err:0,data:{data:data,data1:data1}});
    })
    .catch(data=>{
        res.json({err:3})
    })
})



module.exports = router;